package cn.demoxy.controller;

import cn.demoxy.annotation.Log;
import cn.demoxy.enums.BusinessTypeEnum;
import cn.demoxy.model.dto.DemoUserDTO;
import cn.demoxy.result.R;
import cn.demoxy.service.IDemoUserService;
import cn.demoxy.utils.JWTUtils;
import cn.demoxy.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @auther demo
 * @date 2022/6/22 14:35
 */
@Api(tags = "基础接口信息")
@RestController
@AllArgsConstructor
@CrossOrigin
public class BasicController {

    /**
     * 用户service
     */
    IDemoUserService userService;

    @Autowired
    private RedisUtils redisUtils;



    /**
     * 用户登录
     *
     * @param userDTO
     * @return
     */
    @ApiOperation(value = "用户登录")
    @Log(title = "系统用户登录",businessType = BusinessTypeEnum.LOGIN)
    @PostMapping("/login")
    public R login(@RequestBody DemoUserDTO userDTO) {
        return R.ok(userService.login(userDTO));
    }

    /**
     * 用户登出
     *
     * @param
     * @return
     */
    @ApiOperation(value = "用户登出")
    @Log(title = "系统用户退出登录",businessType = BusinessTypeEnum.LOGOUT)
    @PostMapping("/logout")
    public R logout() {
        Subject subject = SecurityUtils.getSubject();
        String token = subject.getPrincipal().toString();
        String username = JWTUtils.getUsername(token);
        long size = redisUtils.lGetListSize("user");
        for (int i = 0; i < size; i++) {
            Map<String, Object> onlineUser = (Map<String, Object>) redisUtils.lGetIndex("user", i);
            if (onlineUser.get("username").equals(username)) {
                redisUtils.lRemove("user",1,onlineUser);
            }
        }
        subject.logout();
        return R.ok(username);
    }

//    @GetMapping("/ssoLogin")
//    public R ssoLogin(String token){
//        String username = JWTUtils.getUsername(token);
//        long size = redisUtils.lGetListSize("user");
//        for (long i = 0; i < size; i++) {
//            Map<String, Object> onlineUser = (Map<String, Object>) redisUtils.lGetIndex("user", i);
//            if (onlineUser.get("username").equals(username)) {
//                return R.ok();
//            }
//        }
//        return R.fail();
//    }

}
